package com.itboye.eweilisten.util.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;

import com.itboye.eweilisten.R;

import java.util.ArrayList;
import java.util.List;

public class MyFlowLayout extends ViewGroup implements OnClickListener {

    private static final String TAG = "FlowLayout";

    public MyFlowLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected LayoutParams generateLayoutParams(
            LayoutParams p) {
        return new MarginLayoutParams(p);
    }

    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(), attrs);
    }

    @Override
    protected LayoutParams generateDefaultLayoutParams() {
        return new MarginLayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT);
    }

    /**
     * 负责设置子控件的测量模式和大小 根据所有子控件设置自己的宽和高
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        // 获得它的父容器为它设置的测量模式和大小
        int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
        int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
        int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
        int modeHeight = MeasureSpec.getMode(heightMeasureSpec);

        Log.e(TAG, sizeWidth + "," + sizeHeight);

        // 如果是warp_content情况下，记录宽和高
        int width = 0;
        int height = 0;
        /**
         * 记录每一行的宽度，width不断取最大宽度
         */
        int lineWidth = 0;
        /**
         * 每一行的高度，累加至height
         */
        int lineHeight = 0;

        int cCount = getChildCount();

        // 遍历每个子元素
        for (int i = 0; i < cCount; i++) {
            View child = getChildAt(i);
            // 测量每一个child的宽和高
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
            // 得到child的lp
            MarginLayoutParams lp = (MarginLayoutParams) child
                    .getLayoutParams();
            // 当前子空间实际占据的宽度
            int childWidth = child.getMeasuredWidth() + lp.leftMargin
                    + lp.rightMargin;
            // 当前子空间实际占据的高度
            int childHeight = child.getMeasuredHeight() + lp.topMargin
                    + lp.bottomMargin;
            /**
             * 如果加入当前child，则超出最大宽度，则的到目前最大宽度给width，类加height 然后开启新行
             */
            if (lineWidth + childWidth > sizeWidth) {
                width = Math.max(lineWidth, childWidth);// 取最大的
                lineWidth = childWidth; // 重新开启新行，开始记录
                // 叠加当前高度，
                height += lineHeight;
                // 开启记录下一行的高度
                lineHeight = childHeight;
            } else
            // 否则累加值lineWidth,lineHeight取最大高度
            {
                lineWidth += childWidth;
                lineHeight = Math.max(lineHeight, childHeight);
            }
            // 如果是最后一个，则将当前记录的最大宽度和当前lineWidth做比较
            if (i == cCount - 1) {
                width = Math.max(width, lineWidth);
                height += lineHeight;
            }

        }
        setMeasuredDimension((modeWidth == MeasureSpec.EXACTLY) ? sizeWidth
                : width, (modeHeight == MeasureSpec.EXACTLY) ? sizeHeight
                : height);

    }

    /**
     * 存储所有的View，按行记录
     */
    private List<List<View>> mAllViews = new ArrayList<List<View>>();
    /**
     * 记录每一行的最大高度
     */
    private List<Integer> mLineHeight = new ArrayList<Integer>();

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        mAllViews.clear();
        mLineHeight.clear();

        int width = getWidth();

        int lineWidth = 0;
        int lineHeight = 0;
        // 存储每一行所有的childView
        List<View> lineViews = new ArrayList<View>();
        int cCount = getChildCount();
        // 遍历所有的孩子
        for (int i = 0; i < cCount; i++) {
            View child = getChildAt(i);
            MarginLayoutParams lp = (MarginLayoutParams) child
                    .getLayoutParams();
            int childWidth = child.getMeasuredWidth();
            int childHeight = child.getMeasuredHeight();

            // 如果已经需要换行
            if (childWidth + lp.leftMargin + lp.rightMargin + lineWidth > width) {
                // 记录这一行所有的View以及最大高度
                mLineHeight.add(lineHeight);
                // 将当前行的childView保存，然后开启新的ArrayList保存下一行的childView
                mAllViews.add(lineViews);
                lineWidth = 0;// 重置行宽
                lineViews = new ArrayList<View>();
            }
            /**
             * 如果不需要换行，则累加
             */
            lineWidth += childWidth + lp.leftMargin + lp.rightMargin;
            lineHeight = Math.max(lineHeight, childHeight + lp.topMargin
                    + lp.bottomMargin);
            lineViews.add(child);
        }
        // 记录最后一行
        mLineHeight.add(lineHeight);
        mAllViews.add(lineViews);

        int left = 0;
        int top = 0;
        // 得到总行数
        int lineNums = mAllViews.size();
        for (int i = 0; i < lineNums; i++) {
            // 每一行的所有的views
            lineViews = mAllViews.get(i);
            // 当前行的最大高度
            lineHeight = mLineHeight.get(i);

            Log.e(TAG, "第" + i + "行 ：" + lineViews.size() + " , " + lineViews);
            Log.e(TAG, "第" + i + "行， ：" + lineHeight);

            // 遍历当前行所有的View
            for (int j = 0; j < lineViews.size(); j++) {
                View child = lineViews.get(j);
                if (child.getVisibility() == View.GONE) {
                    continue;
                }
                MarginLayoutParams lp = (MarginLayoutParams) child
                        .getLayoutParams();

                //计算childView的left,top,right,bottom
                int lc = left + lp.leftMargin;
                int tc = top + lp.topMargin;
                int rc = lc + child.getMeasuredWidth();
                int bc = tc + child.getMeasuredHeight();

                Log.e(TAG, child + " , l = " + lc + " , t = " + t + " , r ="
                        + rc + " , b = " + bc);

                child.layout(lc, tc, rc, bc);

                left += child.getMeasuredWidth() + lp.rightMargin
                        + lp.leftMargin;
            }
            left = 0;
            top += lineHeight;
        }

    }


    private Context mContext;
    private View mMenuView;
    private List<IText> iTextList = new ArrayList<IText>();
    private boolean isRadio = false;
    private TextView checkedView;// 当前选中的view


    /**
     * 添加标签
     *
     * @param list
     */
    public void addTags(Context mContext, List<String> list) {
        // TODO Auto-generated method stub
        this.mContext = mContext;
        iTextList = addIText(list);
        //MAlert.alert(list.size()+"");
    }

    TextView[] texts = new TextView[2];

    /**
     * 设置选中下标 并添加进布局
     *
     * @param index
     */
    public boolean onSeletorIndex(int index) {
        // TODO Auto-generated method stub
        if (isRadio) {
            return radioSeletorIndex(index);
        } else {
            return seletorIndex(index);
        }
    }

    /**
     * 单选
     *
     * @param index
     * @return
     */
    private boolean radioSeletorIndex(int index) {
        // TODO Auto-generated method stub
        iTextList.get(index).checked = true;
        TextView textView = (TextView) getChildAt(index);
        if (checkedView != null) {
            unCheckedTV(checkedView);
        }
        checkedTV(textView);
        checkedView = textView;
        return true;
    }

    /**
     * 多选 选中view，如果以选中的 则付给它反状态
     *
     * @param index
     */
    private boolean seletorIndex(int index) {
        // TODO Auto-generated method stub
        boolean checked = iTextList.get(index).checked;
        TextView textView = (TextView) getChildAt(index);
        // 赋值给当前选中的view,如果没有选中的则赋值null checkedView
        if (!checked) {
            checkedTV(textView);
            checkedView = textView;
        } else {
            unCheckedTV(textView);
            checkedView = textView;
        }
        // 赋值 反选中 状态
        iTextList.get(index).checked = !checked;
        return !checked;
    }

    /**
     * 初始化view集合,并添加view
     *
     * @param list
     * @return
     */
    private List<IText> addIText(List<String> list) {
        // TODO Auto-generated method stub
        removeAllViews();
        MarginLayoutParams layoutParams = getMarginLayoutParams();
        iTextList = new ArrayList<IText>();
        for (int i = 0; i < list.size(); i++) {
            IText iText = new IText();
            iText.text = getTextView();
            // 添加点击
            iText.text.setOnClickListener(clickListener);
            // 添加 index tag
            iText.text.setTag(i);
            // 给TextView 赋值
            iText.text.setText(list.get(i));
            iText.checked = false;
            iTextList.add(iText);
            unCheckedTV(iText.text);
            addView(iText.text, layoutParams);
        }
        return iTextList;
    }

    /**
     * 获取一个TextView
     *
     * @return
     */
    private TextView getTextView() {
        // TODO Auto-generated method stub
        TextView textView = new TextView(mContext);
        textView.setGravity(Gravity.CENTER);
        textView.setPadding(15, 8, 15, 8);
        return textView;
    }

    /**
     * 未选中
     *
     * @param textView
     */
    private void unCheckedTV(TextView textView) {
        // TODO Auto-generated method stub
        textView.setTextSize(15);
        textView.setTextColor(getColor(R.color.olive_green));
        textView.setBackgroundResource(R.drawable.shape_blue02);
    }

    /**
     * 选中
     *
     * @param textView
     */
    private void checkedTV(TextView textView) {
        // TODO Auto-generated method stub
        textView.setTextSize(15);
        textView.setTextColor(getColor(R.color.white));
        textView.setBackgroundResource(R.drawable.shape_gray);
    }

    /**
     * 获取颜色的简写
     *
     * @param rid
     * @return
     */
    private int getColor(int rid) {
        // TODO Auto-generated method stub
        return mContext.getResources().getColor(rid);
    }

    private MarginLayoutParams getMarginLayoutParams() {
        // TODO Auto-generated method stub
        MarginLayoutParams layoutParams = new MarginLayoutParams(
                LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(15, 8, 15, 8);
        return layoutParams;
    }

    class IText {
        public TextView text;
        public boolean checked = false;
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        int index = (Integer) v.getTag(0);
        String str = (String) v.getTag(1);
    }

    private OnClickListener clickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            int index = (Integer) v.getTag();
            String str = (String) iTextList.get(index).text.getText();
            boolean isChecked = onSeletorIndex(index);
            if (tagOnClickListener != null) {
                tagOnClickListener.tagOnClickListener(index, str, isChecked);
            }
        }
    };

    /**
     * 清除其他所有按钮的状态
     */
    private void clearChecked() {
        // TODO Auto-generated method stub
        int viewCount = getChildCount();
        for (int i = 0; i < texts.length; i++) {
            TextView textView = (TextView) getChildAt(i);
            unCheckedTV(textView);
        }
    }

    /**
     * 设置单选或者多选
     *
     * @param isRadio
     */
    public void setRadio(boolean isRadio) {
        this.isRadio = isRadio;
    }

    /**
     * 设置点击监听事件
     *
     * @param tagOnClickListener
     */
    public void setTagOnClickListener(TagOnClickListener tagOnClickListener) {
        this.tagOnClickListener = tagOnClickListener;
    }

    private TagOnClickListener tagOnClickListener;

    public interface TagOnClickListener {
        /**
         * 单选的时候 isChecked 永远是true 多选的时候才会有 flase
         *
         * @param index
         * @param str
         * @param isChecked
         */
        public void tagOnClickListener(int index, String str, boolean isChecked);
    }


}
